const { DataTypes } = require("sequelize");
const { sequelize } = require("../sequelize");
const Classify = require("./classify");

/* 
1. 表名推断
    默认情况下,当未提供表名时,Sequelize 会自动将模型名复数并将其用作表名.
*/
const Article = sequelize.define(
  "Article",
  {
    // 在这里定义模型属性

    id: {
      //主键
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    uid: {
      // 用户id
      type: DataTypes.INTEGER,
      allowNull: false,
    },
    classifyId: {
      // 分类id
      type: DataTypes.INTEGER,
        allowNull: false,
    },

    title: {
      //文章标题
      type: DataTypes.STRING(36),
      allowNull: false, //不允许为null
      //   unique: true, //唯一约束
      validate: {
        // is: /^[0-9a-f]{64}$/i,
        len: [1, 36],
      },
    },
    content: {
      //文章内容
      type: DataTypes.TEXT,
      allowNull: false,
    },
    cover: {
      //封面图
      type: DataTypes.STRING,
    },
    status: {
      // 文章状态
      type: DataTypes.BOOLEAN,
      defaultValue: 1, // 1 可用 2 禁用
    },
    viewCount: {
      //浏览量
      type: DataTypes.BIGINT,
      defaultValue: 0,
    },
    // viewCount: {//浏览量
    //   type: DataTypes.BIGINT,
    //   defaultValue: 0,
    // },
  },
  {
    // indexes: [{ unique: true, fields: ["name"] }],//sync({alter: true}) throws "Too many keys specified" #9653； 解决该报错
    // 这是其他模型参数
    // freezeTableName: true,//强制表名等于模型名,全局已配置
  }
);

// Article.sync({ alter: true }).then(() => {
//   console.log("用户模型表刚刚(重新)创建！");
// });
// `sequelize.define` 会返回模型
(async () => {
  await sequelize.sync({ alter: true });
  console.log("数据模型同步成功");
})();

Article.hasOne(Classify, {
  foreignKey: "classifyId",
  targetKey: "id",
  //   关联关系,但不创建外键
  constraints: false,
});
Classify.belongsTo(Article, {
  foreignKey: "classifyId",
  targetKey: "id",
  //   关联关系,但不创建外键
  constraints: false,
});

// Article.create({uid:16,title:'测试',content:'擦宽松的环境卡死',status:1,viewCount:100})
// Article.create({uid:16,title:'测试',content:'擦宽松的环境卡死',status:1,viewCount:100})
// Article.create({uid:16,title:'测试',content:'擦宽松的环境卡死',status:1,viewCount:100})
// Article.create({uid:16,title:'测试',content:'擦宽松的环境卡死',status:1,viewCount:100})
// Article.create({uid:16,title:'测试',content:'擦宽松的环境卡死',status:1,viewCount:100})

console.log(Article === sequelize.models.Article); // true

module.exports = Article;
